import React, {
  forwardRef,
  useCallback,
  useEffect,
  useMemo,
  useRef,
} from 'react';
import type { MicroAppRef, MicroBizWidgetProps } from '../../types';
import BasicMicroApp from './BasicMicroApp';

// 组件内部名称计数器
let NAME_ID = 0;

/**
 * 业务组件微应用
 *
 * 功能特性：
 * - 继承 BasicMicroApp 的所有功能
 * - 支持动态尺寸调整
 * - 提供尺寸变化事件
 * - 支持响应式布局
 * - 自动生成唯一组件名称
 */
const MicroBizWidget = forwardRef<MicroAppRef, MicroBizWidgetProps>(
  (
    {
      width,
      height,
      minWidth = 400,
      minHeight,
      maxWidth,
      maxHeight,
      resizable = false,
      onResize,
      style,
      url,
      defaultPage,
      onDataChange,
      name: _ignoredName, // eslint-disable-line @typescript-eslint/no-unused-vars
      ...props
    },
    ref,
  ) => {
    const containerRef = useRef<HTMLDivElement>(null);

    // 生成唯一的微应用名称
    const microName = useMemo(() => {
      NAME_ID += 1;
      return `biz-widget-${NAME_ID}`;
    }, []);

    // 计算组件尺寸
    const computedSize = useMemo(() => {
      let computedWidth = width;
      let computedHeight = height;

      // 如果没有指定宽度，使用容器宽度或最小宽度
      if (!computedWidth) {
        computedWidth = minWidth;
      }

      // 处理最小/最大宽度约束
      if (typeof computedWidth === 'number') {
        if (typeof minWidth === 'number' && computedWidth < minWidth) {
          computedWidth = minWidth;
        }
        if (typeof maxWidth === 'number' && computedWidth > maxWidth) {
          computedWidth = maxWidth;
        }
      }

      // 如果没有指定高度，根据宽度计算（保持宽高比）
      if (!computedHeight && typeof computedWidth === 'number') {
        computedHeight = computedWidth * 0.85; // 默认宽高比
      }

      // 处理最小/最大高度约束
      if (typeof computedHeight === 'number') {
        if (typeof minHeight === 'number' && computedHeight < minHeight) {
          computedHeight = minHeight;
        }
        if (typeof maxHeight === 'number' && computedHeight > maxHeight) {
          computedHeight = maxHeight;
        }
      }

      return { width: computedWidth, height: computedHeight };
    }, [width, height, minWidth, minHeight, maxWidth, maxHeight]);

    // 处理尺寸变化
    const handleResize = useCallback(
      (newWidth: number, newHeight: number) => {
        if (onResize) {
          onResize(newWidth, newHeight);
        }
      },
      [onResize],
    );

    // 监听容器尺寸变化（如果启用了自适应）
    useEffect(() => {
      if (!resizable || !containerRef.current) return;

      const resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          const { width: newWidth, height: newHeight } = entry.contentRect;
          handleResize(newWidth, newHeight);
        }
      });

      resizeObserver.observe(containerRef.current);

      return () => {
        resizeObserver.disconnect();
      };
    }, [resizable, handleResize]);

    // 处理数据变化
    const handleDataChange = useCallback(
      (event: CustomEvent) => {
        console.log('业务组件数据变化:', event.detail?.data);
        if (onDataChange) {
          onDataChange(event);
        }
      },
      [onDataChange],
    );

    // 组件样式
    const componentStyle: React.CSSProperties = {
      width: computedSize.width,
      height: computedSize.height,
      overflow: 'hidden',
      position: 'relative',
      resize: resizable ? 'both' : 'none',
      minWidth,
      minHeight,
      maxWidth,
      maxHeight,
      ...style,
    };

    return (
      <div ref={containerRef} style={componentStyle}>
        <BasicMicroApp
          ref={ref}
          name={microName}
          url={url}
          defaultPage={defaultPage}
          style={{
            width: '100%',
            height: '100%',
          }}
          onDataChange={handleDataChange}
          {...props}
        />
      </div>
    );
  },
);

MicroBizWidget.displayName = 'MicroBizWidget';

export default MicroBizWidget;
